package com.lz.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lz.blog.dao.dos.Archives;
import com.lz.blog.dao.mapper.ArticleBodyMapper;
import com.lz.blog.dao.mapper.ArticleMapper;
import com.lz.blog.dao.mapper.CategoryMapper;
import com.lz.blog.dao.mapper.TagMapper;
import com.lz.blog.dao.pojo.Article;
import com.lz.blog.dao.pojo.ArticleBody;
import com.lz.blog.dao.pojo.Category;
import com.lz.blog.service.ArticleService;
import com.lz.blog.service.SysUserService;
import com.lz.blog.service.TagService;
import com.lz.blog.service.ThreadService;
import com.lz.blog.vo.ArticleBodyVo;
import com.lz.blog.vo.ArticleVo;
import com.lz.blog.vo.Result;
import com.lz.blog.vo.TagVo;
import com.lz.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private TagService tagService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ArticleBodyMapper articleBodyMapper;
    @Resource
    private TagMapper tagMapper;
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private ThreadService threadService;

    @Override
    public Result listArticle(PageParams pageParams) {
        /**
         * 1、分页查询 article数据库表
         */
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //是否置顶进行排序
        //order by create_date desc
        queryWrapper.orderByDesc(Article::getWeight, Article::getCreateDate);

        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
        List<Article> records = articlePage.getRecords();
        //不能直接返回,数据库与前端页面返回的内容不一定相同，故使用VO类
        //将数据先进行转移
        List<ArticleVo> articleVoList = copyList(records, true, true);
        return Result.success(articleVoList);
    }


    //对内容进行转移  从 article->articleVo
    private List<ArticleVo> copyList(List<Article> records, boolean isTag, boolean isAuthor) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isTag, isAuthor));
        }
        return articleVoList;
    }

    //对内容进行复制传值
    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);
        //articleVo与article类的时间数据类型不兼容，进行一个转换
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //不是所有的接口都需要标签，作者信息
        if (isTag) {
            Long id = article.getId();
            articleVo.setTags(tagService.findTagsByArticleId(id));
        }
        if (isAuthor) {
            Long authorId = article.getAuthorId();
            articleVo.setAuthor(sysUserService.findUserById(authorId).getNickname());
        }
        return articleVo;
    }


    /**
     * 最热文章
     *
     * @param limit
     * @return
     */
    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //对浏览量进行排序
        queryWrapper.orderByDesc(Article::getViewCounts);
        //接口文档说明只需获取两列
        queryWrapper.select(Article::getId, Article::getTitle);
        //用来限制条数
        queryWrapper.last("limit " + limit);
        //降序
        //select id,title from ms_article order by view_counts desc limit 5
        List<Article> articles = articleMapper.selectList(queryWrapper);

        return Result.success(copyList(articles, false, false));
    }

    /**
     * 最新文章显示
     *
     * @param limit
     * @return
     */
    @Override
    public Result newArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId, Article::getTitle, Article::getCreateDate);
        queryWrapper.last("limit 10");
//        queryWrapper.last("limit "+limit);
        //select id,title,create_date from ms_article order by create_date desc limit 3
        List<Article> articles = articleMapper.selectList(queryWrapper);

        return Result.success(copyList(articles, false, false));
    }

    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();
        return Result.success(archivesList);
    }

    @Override
    public Result findArticleById(Long articleId) {
        /**
         * 1、根据ID查询文章信息
         * 2、根据bodyId和categoryId
         */
        Article article = articleMapper.selectById(articleId);

        ArticleVo articleVo = this.copy(article, true, true);
        Long id = article.getId();
        //查询文章体的内容
        LambdaQueryWrapper<ArticleBody> articleBodyQueryWrapper = new LambdaQueryWrapper<>();
        articleBodyQueryWrapper.eq(ArticleBody::getArticleId, id)
                .select(ArticleBody::getContent)
                .last("limit 1");
        ArticleBody articleBody = articleBodyMapper.selectOne(articleBodyQueryWrapper);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        //查询标签内容
        List<TagVo> tagVoList = tagMapper.findTagsVoByArticleId(id);
        //查询分类内容
        Category category = categoryMapper.findCategoryById(id);
        articleVo.setBody(articleBodyVo);
        articleVo.setTags(tagVoList);
        articleVo.setCategory(category);
        //查看完文章后，新增阅读数，会有问题？
        //查看完文章后，本应该直接返回数据，这时做了更新操作，更新时加写锁，阻塞了其他读的操作 降低了效率
        //做更新操作也增加了此次接口耗时  如果更新操作
        //方法：将更新操作放入线程池中
        threadService.updateArticleViewCount(articleMapper,article);
        return Result.success(articleVo);
    }
}
